package cn.tedu.vue_master.config;


import cn.tedu.vue_master.filter.JwtAuthorizationFilter;
import cn.tedu.vue_master.security.SSOFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    /*@Autowired
        private JwtAuthorizationFilter jwtAuthorizationFilter;*/

    @Autowired
    private SSOFilter ssoFilter;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 白名单
        String[] urls = {
                "/doc.html",
                "/favicon.ico",
                "/**/*.js",
                "/**/*.css",
                "/swagger-resources",
                "/v2/api-docs",
                "/users/login",
                "/testController/**",
                "/restTemplate/test" //获取oauth认证
        };

        // 配置各请求路径是否需要通过认证
        http.authorizeRequests() // 对请求进行授权
                .antMatchers(urls) // 匹配某些路径
                .permitAll() // 允许此前匹配的路径直接访问，不需要通过认证或授权
                // .antMatchers(HttpMethod.OPTIONS,"/**")
                // .permitAll()
                .anyRequest() // 除了以上配置过的其它任何路径
                .authenticated(); // 需要通过认证

        // 允许跨域访问
        http.cors(); // 激活Spring Security框架内置的一个CorsFilter，允许跨域访问

        http.csrf().disable();
        // 将JWT过滤器添加在Spring Security的UsernamePasswordAuthenticationFilter之前
        http.addFilterBefore(ssoFilter,
                UsernamePasswordAuthenticationFilter.class);
        //http.formLogin();
    }

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        // 调用父类的方法得到AuthenticationManager
        return super.authenticationManager();
    }
}
